package net.cjw.initsb.service.impl;

import java.security.spec.RSAKeyGenParameterSpec;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;

import net.cjw.initsb.common.ServiceResult;
import net.cjw.initsb.common.ServiceResult.ServiceResultMsg;
import net.cjw.initsb.dao.ManageUserMapper;
import net.cjw.initsb.dao.RoleUserConnectMapper;
import net.cjw.initsb.entity.ManageUser;
import net.cjw.initsb.entity.Role;
import net.cjw.initsb.entity.RoleUserConnect;
import net.cjw.initsb.service.FileServiceI;
import net.cjw.initsb.service.ManageUserServiceI;
import net.cjw.initsb.utils.MD5Util;
import net.cjw.initsb.utils.PasswordUtils;
import net.cjw.initsb.utils.UUIDBuild;
import net.cjw.initsb.vo.ManageUserVo;

@Service
@Transactional
public class ManageUserServiceImpl implements ManageUserServiceI {

	Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private ManageUserMapper manageUserMapper;
	@Autowired
	private RoleUserConnectMapper roleUserConnectMapper;

	@Override
	public ServiceResult<String> login(ManageUser user) {
		ManageUser tmp;
		ManageUser rs;
		tmp = new ManageUser();
		tmp.setUsername(user.getUsername());
		rs = manageUserMapper.selectOne(tmp);
		if (rs == null) {
			return ServiceResult.buildError(ServiceResultMsg.LOGIN_ERROR_MSG);
		}
		if (rs.getIsDelete()) {
			return ServiceResult.buildError("账号以被删除");
		}
		if (rs.getIsDisable()) {
			return ServiceResult.buildError("账号以被禁用");
		}
		tmp = new ManageUser();
		tmp.setUsername(user.getUsername());
		String md5password = PasswordUtils.buildPassword(user.getPassword(), rs.getSalt());
		tmp.setPassword(md5password);
		rs = manageUserMapper.selectOne(tmp);
		if (rs != null) {

			logger.info("加入shiro登录验证");
			try {
				UsernamePasswordToken upt = new UsernamePasswordToken(user.getUsername(), md5password);
				Subject subject = SecurityUtils.getSubject();
				subject.login(upt);
			} catch (Exception e) {
				return ServiceResult.buildError(ServiceResultMsg.LOGIN_ERROR_MSG);
			}
			String uid = rs.getId();
			return ServiceResult.buildSuccess(uid);
		}
		return ServiceResult.buildError(ServiceResultMsg.LOGIN_ERROR_MSG);
	}

	@Override
	public ServiceResult<String> create(ManageUser user) {
		// 验证
		ManageUser tmp;
		tmp = new ManageUser();
		tmp.setUsername(user.getUsername());
		tmp = manageUserMapper.selectOne(tmp);
		if (tmp != null) {
			return ServiceResult.buildError("账号以被使用");
		}
		tmp = new ManageUser();
		tmp.setNickname(user.getNickname());
		tmp = manageUserMapper.selectOne(tmp);
		if (tmp != null) {
			return ServiceResult.buildError("昵称以被使用");
		}
		// 存头像
		if (Strings.isNullOrEmpty(user.getAvatarUrl())) {

			user.setAvatarUrl("/common/image/default_user_avatar.jpg");
		}
		// 插入
		user.setId(UUIDBuild.createUUId());
		user.setCreateTime(new Date());

		user.setNickname(user.getNickname());
		String salt = PasswordUtils.buildSalt();
		user.setSalt(salt);
		user.setPassword(PasswordUtils.buildPassword(user.getPassword(), salt));
		user.setUsername(user.getUsername());
		int i = manageUserMapper.insertSelective(user);
		if (i > 0) {
			return ServiceResult.buildSuccess(null);
		}
		return ServiceResult.buildError(ServiceResultMsg.SERVER_ERROR_MSG);
	}

	@Override
	public ServiceResult<String> update(ManageUser user) {
		ManageUser tmp;
		ManageUser rs;

		tmp = new ManageUser();
		tmp.setId(user.getId());
		rs = manageUserMapper.selectOne(tmp);
		if (rs == null) {
			return ServiceResult.buildError("找不到对象");
		}
		if (!Strings.isNullOrEmpty(user.getNickname()) && !user.getNickname().equals(rs.getNickname())) {
			tmp = new ManageUser();
			tmp.setNickname(user.getNickname());
			rs = manageUserMapper.selectOne(tmp);
			if (rs == null) {
				return ServiceResult.buildError("昵称以被使用");
			}
		}
		if (!Strings.isNullOrEmpty(user.getPassword())) {
			String salt = PasswordUtils.buildSalt();
			user.setSalt(salt);
			user.setPassword(PasswordUtils.buildPassword(user.getPassword(), salt));
		}

		int i = manageUserMapper.updateByPrimaryKeySelective(user);
		if (i > 0) {
			return ServiceResult.buildSuccess(null);
		}
		return ServiceResult.buildError(ServiceResultMsg.SERVER_ERROR_MSG);
	}

	@Override
	public ServiceResult<String> delete(ManageUser entity) {
		ManageUser tmp;
		ManageUser rs;
		tmp = new ManageUser();
		tmp.setId(entity.getId());
		rs = manageUserMapper.selectOne(tmp);
		if (rs == null) {
			return ServiceResult.buildError("找不到删除的对象");
		}
		rs.setIsDelete(true);
		manageUserMapper.updateByPrimaryKey(rs);
		return ServiceResult.buildSuccess();
	}

	@Override
	public ServiceResult<ManageUser> selectOne(ManageUser entity) {
		ManageUser user = manageUserMapper.selectOne(entity);
		if (user == null) {
			return ServiceResult.buildError("查询不到用户");
		}
		ManageUser vo = new ManageUser();
		vo.setAvatarUrl(user.getAvatarUrl());
		vo.setCreateTime(user.getCreateTime());
		vo.setId(user.getId());
		vo.setNickname(user.getNickname());
		return ServiceResult.buildSuccess(vo);
	}

	@Override
	public ServiceResult<Object> selectAll(Integer start, Integer max) {
		PageHelper page = new PageHelper();
		page.startPage(start, max);
		List<Map<String, Object>> list = manageUserMapper.selectAllSubtractPassword();
		PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(list);
		return ServiceResult.buildSuccess(list, pageInfo.getTotal());
	}

	@Override
	public ServiceResult<ManageUserVo> info(ManageUser user) {
		ManageUser rs;
		rs = manageUserMapper.selectOne(user);

		if (rs == null) {

			return ServiceResult.buildError("找不到管理员");
		} else {
			rs.setPassword(null);
		}

		return ServiceResult.buildSuccess(new ManageUserVo(rs.getNickname(), rs.getAvatarUrl(), rs.getLoginTime()));
	}

	@Override
	public ServiceResult<String> create(ManageUser user, String roleId) {
		// 验证
		ManageUser tmp;
		tmp = new ManageUser();
		tmp.setUsername(user.getUsername());
		tmp = manageUserMapper.selectOne(tmp);
		if (tmp != null) {
			return ServiceResult.buildError("账号以被使用");
		}
		tmp = new ManageUser();
		tmp.setNickname(user.getNickname());
		tmp = manageUserMapper.selectOne(tmp);
		if (tmp != null) {
			return ServiceResult.buildError("昵称以被使用");
		}
		// 存头像
		if (Strings.isNullOrEmpty(user.getAvatarUrl())) {

			user.setAvatarUrl("/common/image/default_user_avatar.jpg");
		}
		// 插入
		user.setId(UUIDBuild.createUUId());
		user.setCreateTime(new Date());

		user.setNickname(user.getNickname());
		String salt = PasswordUtils.buildSalt();
		user.setSalt(salt);
		user.setPassword(PasswordUtils.buildPassword(user.getPassword(), salt));
		user.setUsername(user.getUsername());
		int i = manageUserMapper.insertSelective(user);
		if (i > 0) {
			return ServiceResult.buildSuccess(null);
		}
		// 绑定
		RoleUserConnect ru = new RoleUserConnect();
		ru.setId(UUIDBuild.createUUId());
		ru.setCreateTime(new Date());
		ru.setUid(user.getId());
		ru.setRoleId(roleId);
		roleUserConnectMapper.insert(ru);
		return ServiceResult.buildError(ServiceResultMsg.SERVER_ERROR_MSG);
	}

	@Override
	public ServiceResult<String> update(ManageUser user, String roleId) {
		ManageUser tmp;
		ManageUser rs;

		tmp = new ManageUser();
		tmp.setId(user.getId());
		rs = manageUserMapper.selectOne(tmp);
		if (rs == null) {
			return ServiceResult.buildError("找不到对象");
		}
		if (!Strings.isNullOrEmpty(user.getNickname()) && !user.getNickname().equals(rs.getNickname())) {
			tmp = new ManageUser();
			tmp.setNickname(user.getNickname());
			rs = manageUserMapper.selectOne(tmp);
			if (rs != null) {
				return ServiceResult.buildError("昵称以被使用");
			}
		}
		if (!Strings.isNullOrEmpty(user.getPassword())) {
			String salt = PasswordUtils.buildSalt();
			user.setSalt(salt);
			user.setPassword(PasswordUtils.buildPassword(user.getPassword(), salt));
		}

		int i = manageUserMapper.updateByPrimaryKeySelective(user);
		if (i > 0) {
			return ServiceResult.buildSuccess(null);
		}

		if (!Strings.isNullOrEmpty(roleId)) {
			// 解绑
			RoleUserConnect ru = new RoleUserConnect();
			ru.setUid(user.getId());
			roleUserConnectMapper.delete(ru);
			// 绑定
			ru.setRoleId(roleId);
			ru.setId(UUIDBuild.createUUId());
			ru.setCreateTime(new Date());
			roleUserConnectMapper.insert(ru);
		}
		return ServiceResult.buildError(ServiceResultMsg.SERVER_ERROR_MSG);
	}
}
